// 导入vue
import Vue from 'vue'

// 1 导入 vue-router
import VueRouter from 'vue-router'

// 5 导入组件
//  .vue 后缀可省略
import Home from '@/components/home/Home'
import Login from '@/components/login/Login'
import Users from '@/components/users/Users'
import Roles from '@/components/roles/Roles'
import Rights from '@/components/rights/Rights'
import Goods from '@/components/goods/Goods'
import Params from '@/components/params/Params'
import Categories from '@/components/categories/Categories'
import Orders from '@/components/orders/Orders'
import Reports from '@/components/reports/Reports'
import GoodsAdd from '@/components/goods-add/GoodsAdd'
// 导入 404 组件
import NotFound from '@/components/notfound/NotFound'
// 2 将路由作为Vue的插件安装
Vue.use(VueRouter)
// 3 创建路由实例，配置路由
const router = new VueRouter({
  routes: [
    // 默认路由，重定向到 /home
    { path: '/', redirect: '/home' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      children: [
        { path: '/users', component: Users },
        { path: '/roles', component: Roles },
        { path: '/rights', component: Rights },
        /*
          /goods/:page 表示使用了路由参数，用来动态匹配哈希值
          :page 就是路由参数，我们使用这个参数，来匹配分页数值

          :page? 表示这路由参数是可选的，可以有，也可以没有，这样就可以匹配：
          1 /goods
          2 /goods/6
        */
        { path: '/goods/:page?', component: Goods },
        { path: '/params', component: Params },
        { path: '/categories', component: Categories },
        { path: '/orders', component: Orders },
        { path: '/reports', component: Reports },
        { path: '/goods-add', component: GoodsAdd }
      ]
    },
    { path: '*', component: NotFound }
  ]
})

// 添加导航首位，用来实现登陆访问限制
// 说明：每次切换路由（访问页面），都会先执行导航守卫，那么，是否登录的逻辑判断就可以放在
// 导航守卫中判断了
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
  // 是登陆页面，直接进入到要访问的登陆页面
    return next()
  }
  // 不是登陆页面
  const token = localStorage.getItem('token')
  if (token) {
    // 登陆过
    next()
  } else {
    // 没有登陆过
    next('/login')
  }
})

// 导出路由实例
export default router
